package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.StockCheck;
import com.geek.factory.entity.StockCheckAdjustment;
import com.geek.factory.entity.StockCheckDetail;
import com.geek.factory.result.Result;
import com.geek.factory.service.IStockCheckAdjustmentService;
import com.geek.factory.service.IStockCheckDetailService;
import com.geek.factory.service.IStockCheckService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 库存盘点差异处理管理控制器
 */
@RestController
@RequestMapping("/stock-check-adjustment")
@Api(tags = "后台系统的 - 库存盘点差异处理模块")
@Slf4j
@CrossOrigin
public class StockCheckAdjustmentController {

    @Autowired
    private IStockCheckAdjustmentService stockCheckAdjustmentService;

    @Autowired
    private IStockCheckDetailService stockCheckDetailService;

    @Autowired
    private IStockCheckService stockCheckService;

    @ApiOperation("通过ID查询库存盘点差异处理信息")
    @GetMapping("/{adjustmentId}")
    public Result findStockCheckAdjustmentById(@ApiParam("差异处理ID") @PathVariable("adjustmentId") Integer adjustmentId) {
        StockCheckAdjustment adjustment = stockCheckAdjustmentService.getById(adjustmentId);
        log.info("adjustment: {}", adjustment);
        if (adjustment != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", adjustment);
        }
        return new Result(SuccessConstant.FAIL, "库存盘点差异处理记录不存在");
    }

    @ApiOperation("新增库存盘点差异处理")
    @PostMapping
    public Result addStockCheckAdjustment(@RequestBody StockCheckAdjustment adjustment) {
        // 设置默认值
        adjustment.setCreatedTime(LocalDateTime.now());

        // 验证必填字段
        if (adjustment.getDetailId() == null) {
            return new Result(SuccessConstant.FAIL, "盘点明细ID不能为空");
        }
        if (StringUtils.isBlank(adjustment.getAdjustmentType())) {
            return new Result(SuccessConstant.FAIL, "差异类型不能为空");
        }
        if (adjustment.getAdjustmentQuantity() == null) {
            return new Result(SuccessConstant.FAIL, "调整数量不能为空");
        }

        // 获取明细信息
        StockCheckDetail detail = stockCheckDetailService.getById(adjustment.getDetailId());
        if (detail == null) {
            return new Result(SuccessConstant.FAIL, "盘点明细不存在");
        }
        adjustment.setCheckId(detail.getCheckId());

        boolean isSuccess = stockCheckAdjustmentService.save(adjustment);
        log.info("新增库存盘点差异处理: {}, 结果: {}", adjustment, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "新增成功", adjustment);
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }

    @ApiOperation("根据ID删除库存盘点差异处理")
    @DeleteMapping("/{adjustmentId}")
    public Result deleteStockCheckAdjustment(@ApiParam("差异处理ID") @PathVariable("adjustmentId") Integer adjustmentId) {
        // 检查是否可编辑
        if (!stockCheckAdjustmentService.isAdjustmentEditable(adjustmentId)) {
            return new Result(SuccessConstant.FAIL, "该差异处理记录已审批，不能删除");
        }

        boolean isSuccess = stockCheckAdjustmentService.removeById(adjustmentId);
        log.info("删除库存盘点差异处理ID: {}, 结果: {}", adjustmentId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    @ApiOperation("修改库存盘点差异处理信息")
    @PutMapping("/{adjustmentId}")
    public Result updateStockCheckAdjustment(@ApiParam("差异处理ID") @PathVariable("adjustmentId") Integer adjustmentId, @RequestBody StockCheckAdjustment adjustment) {
        // 检查是否可编辑
        if (!stockCheckAdjustmentService.isAdjustmentEditable(adjustmentId)) {
            return new Result(SuccessConstant.FAIL, "该差异处理记录已审批，不能修改");
        }

        adjustment.setAdjustmentId(adjustmentId);
        adjustment.setUpdatedTime(LocalDateTime.now());

        boolean isSuccess = stockCheckAdjustmentService.updateById(adjustment);
        log.info("修改库存盘点差异处理: {}, 结果: {}", adjustment, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", adjustment);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @ApiOperation("审批差异处理")
    @PutMapping("/{adjustmentId}/approve")
    public Result approveAdjustment(
            @ApiParam("差异处理ID") @PathVariable("adjustmentId") Integer adjustmentId,
            @RequestBody Map<String, String> request
    ) {
        String approvedBy = request.get("approvedBy");
        String approvalResult = request.get("approvalResult");
        String approvalComments = request.get("approvalComments");

        if (StringUtils.isBlank(approvedBy)) {
            return new Result(SuccessConstant.FAIL, "审批人不能为空");
        }
        if (StringUtils.isBlank(approvalResult)) {
            return new Result(SuccessConstant.FAIL, "审批结果不能为空");
        }

        boolean isSuccess = stockCheckAdjustmentService.approveAdjustment(adjustmentId, approvedBy, approvalResult, approvalComments);
        log.info("审批差异处理: adjustmentId={}, approvedBy={}, approvalResult={}, 结果: {}",
                adjustmentId, approvedBy, approvalResult, isSuccess);
        if (isSuccess) {
            StockCheckAdjustment adjustment = stockCheckAdjustmentService.getById(adjustmentId);
            return new Result(SuccessConstant.SUCCESS, "审批成功", adjustment);
        }
        return new Result(SuccessConstant.FAIL, "审批失败");
    }

    @ApiOperation("根据盘点明细ID查询差异处理记录")
    @GetMapping("/detail/{detailId}")
    public Result getAdjustmentsByDetailId(@ApiParam("盘点明细ID") @PathVariable("detailId") Integer detailId) {
        List<StockCheckAdjustment> adjustments = stockCheckAdjustmentService.getAdjustmentsByDetailId(detailId);
        return new Result(SuccessConstant.SUCCESS, "查询成功", adjustments);
    }

    @ApiOperation("根据盘点单ID查询差异处理记录")
    @GetMapping("/check/{checkId}")
    public Result getAdjustmentsByCheckId(@ApiParam("盘点单ID") @PathVariable("checkId") Integer checkId) {
        List<StockCheckAdjustment> adjustments = stockCheckAdjustmentService.getAdjustmentsByCheckId(checkId);
        return new Result(SuccessConstant.SUCCESS, "查询成功", adjustments);
    }

    @ApiOperation("分页查询库存盘点差异处理列表")
    @GetMapping("/page")
    public Result getStockCheckAdjustmentPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer checkId,
            @RequestParam(required = false) Integer detailId,
            @RequestParam(required = false) String adjustmentType,
            @RequestParam(required = false) String approvalResult
    ) {
        QueryWrapper<StockCheckAdjustment> wrapper = new QueryWrapper<>();
        if (checkId != null) {
            wrapper.eq("check_id", checkId);
        }
        if (detailId != null) {
            wrapper.eq("detail_id", detailId);
        }
        if (StringUtils.isNotBlank(adjustmentType)) {
            wrapper.eq("adjustment_type", adjustmentType);
        }
        if (StringUtils.isNotBlank(approvalResult)) {
            wrapper.eq("approval_result", approvalResult);
        }
        wrapper.orderByDesc("created_time");

        Page<StockCheckAdjustment> page = stockCheckAdjustmentService.page(new Page<>(pageNum, pageSize), wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        data.put("current", page.getCurrent());
        data.put("size", page.getSize());
        data.put("pages", page.getPages());

        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("获取差异处理统计信息")
    @GetMapping("/stats/{checkId}")
    public Result getAdjustmentStats(@ApiParam("盘点单ID") @PathVariable("checkId") Integer checkId) {
        Map<String, Object> stats = stockCheckAdjustmentService.getAdjustmentStats(checkId);
        return new Result(SuccessConstant.SUCCESS, "查询成功", stats);
    }

    @ApiOperation("创建差异处理记录")
    @PostMapping("/create")
    public Result createAdjustment(@RequestBody Map<String, Object> params) {
        Integer detailId = (Integer) params.get("detailId");
        String adjustmentType = (String) params.get("adjustmentType");
        BigDecimal adjustmentQuantity = new BigDecimal(params.get("adjustmentQuantity").toString());
        String reason = (String) params.get("reason");
        String createdBy = (String) params.get("createdBy");

        if (detailId == null) {
            return new Result(SuccessConstant.FAIL, "盘点明细ID不能为空");
        }
        if (StringUtils.isBlank(adjustmentType)) {
            return new Result(SuccessConstant.FAIL, "差异类型不能为空");
        }
        if (adjustmentQuantity == null) {
            return new Result(SuccessConstant.FAIL, "调整数量不能为空");
        }
        if (StringUtils.isBlank(createdBy)) {
            return new Result(SuccessConstant.FAIL, "创建人不能为空");
        }

        StockCheckAdjustment adjustment = stockCheckAdjustmentService.createAdjustment(
                detailId, adjustmentType, adjustmentQuantity, reason, createdBy);

        if (adjustment != null) {
            return new Result(SuccessConstant.SUCCESS, "创建成功", adjustment);
        }
        return new Result(SuccessConstant.FAIL, "创建失败");
    }
}